import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Modal,
  Badge,
  Divider,
  Table,
  Dropdown,
  Menu,
  Upload,
  Icon,
  DatePicker,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../search.less';
import UploadFileForm from '../Client/sub/UploadFileForm';
import moment from 'moment';
const FormItem = Form.Item;
const { Option } = Select;
const vmisforce = ['强制升级','建议升级'];
const vmpackagetype = ['全量包','增量包'];
const formLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 17 },
};
const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    handleAdd,
    handleModalVisible,
    setPath,
    path
  } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if (!path) {
        Modal.warning({title: '操作失败',content: '请选择上传升级包'});
      }else{
        handleAdd();
      }

    });
  };
  return (
    <Modal
      destroyOnClose
      width={640}
      title="新增版本"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <div style={{textAlign:'center'}}>
        <UploadFileForm setPath={setPath}
        />
      </div>
    </Modal>
  );
});
/* eslint react/no-multi-comp:0 */
@connect(({ versionMag, loading }) => ({
  versionMag,
  loading: loading.models.versionMag,
}))
@Form.create()
class versionMag extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    text: {},
    path: '',
    upGradeList: {}
  };

  columns = [
    {
      title: '业务名称',
      dataIndex: 'bmname',
      width:"10%",
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    {
      title: '版本号',
      dataIndex: 'vmvernum',
    },
    {
      title: '升级模式',
      dataIndex: 'vmisforce',
      width:"10%",
      render: (text) => (
        <div className={styles.colRemark} title={vmisforce[text]}>
          {vmisforce[text]}
        </div>
      )
    },
    {
      title: '升级包类型',
      dataIndex: 'vmpackagetype',
      width:"10%",
      render: (text) => (
        <div className={styles.colRemark} title={vmpackagetype[text]}>
          {vmpackagetype[text]}
        </div>
      )
    },
    {
      title: '升级包HASH值',
      dataIndex: 'vmpackagehash',
      width:"20%",
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    {
      title: '升级包相对路径',
      dataIndex: 'vmftppath',
      width:"20%",
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    {
      title: 'BC文件HASH值',
      dataIndex: 'vmbchash',
      width:"20%",
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    {
      title: '升级包大小',
      dataIndex: 'vmpackagesize',
    },
    {
      title: '发布日期',
      dataIndex: 'vmpublishdate',
    },
    {
      title: '上传日期',
      dataIndex: 'vmuploaddate',
    },
    {
      title: '操作',
      width:"20%",
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleDetailModalVisible(true,record)}>详情</a>
          <Divider type="vertical" />
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item onClick={() => this.deleteData(text.id)}>删除</Menu.Item>
                <Menu.Item onClick={() => this.handleUpgradeListModalVisible(true,record)}>升级记录</Menu.Item>
              </Menu>
            }
          >
            <a>更多 <Icon type="down"/></a>
          </Dropdown>
        </Fragment>
      ),
    },
  ];

  setPath(path) {
    this.setState({
      path
    })
  }

  componentDidMount() {
    this.pageList();
  }
  // 分页查询列表
  pageList(data,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      bmname: data && data.bmname || '',
      vmuploaddate: data && data.vmuploaddate || '',
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'versionMag/queryList',
      payload: values,
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues,pagination.pageSize,pagination.current-1);
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };


  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };
  batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };
  handleThisRowDelete = (id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'versionMag/remove',
      payload: {id},
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },//callback
    });
  }

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        vmuploaddate: fieldsValue.vmuploaddate&&moment(fieldsValue.vmuploaddate).format('YYYY-MM-DD')||'',
      };
      this.setState({
        formValues: values,
      });
      this.pageList(values);
    });
  };


  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      editFormValues: record || {},
    });
  };

  handleDetailModalVisible = (flag,text) => {
    this.setState({
      detailModalVisible: !!flag,
      text
    });
  };

  handleUpgradeListModalVisible = (flag,text) => {
    this.setState({
      upgradeListModalVisible: !!flag,
      text,
    });
    if(flag){
      this.getUpGrade(text)
    }
  };

  //升级记录请求
   getUpGrade= (data,pageSize=10,pageNum=0) => {
    const { dispatch } = this.props;
    const values = {
      currentTerminalVersion: data&&data.vmvernum||'',
      busName: data&&data.bmname||'',
      pageSize,
      pageNum,
    }
    dispatch({
      type: 'versionMag/upGrade',
      payload: values,
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            upGradeList: res.data
          })
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
        this.setState({
          path:''
        })
      },
    });
    this.handleModalVisible();
  };

  //新增
  handleAdd = () => {
    const { dispatch } = this.props;
    const { path } = this.state;
    dispatch({
      type: 'versionMag/add',
      payload: { path },
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList()
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
        this.setState({
          path:''
        })
      },
    });
    this.handleModalVisible();
  };

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="业务名称">
              {getFieldDecorator('bmname')(<Input placeholder=""/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="上传日期">
              {getFieldDecorator('vmuploaddate')(
                <DatePicker
                  format={'YYYY-MM-DD'}
                />
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      versionMag: { data },
      loading,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      editFormValues,
      detailModalVisible,
      text,
      upgradeListModalVisible,
      upGradeList,
      path
    } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd.bind(this),
      handleModalVisible: this.handleModalVisible,
      setPath: this.setPath.bind(this),
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    const detailsMethods = {
      handleDetailModalVisible: this.handleDetailModalVisible,
    };
    const upgradeListMethods = {
      handleUpgradeListModalVisible: this.handleUpgradeListModalVisible,
      getUpGrade: this.getUpGrade.bind(this),
    };

    return (
      <Card bordered={false}>
        <CreateForm {...parentMethods} modalVisible={modalVisible} path={path} />
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
            )}
          </div>
          <TableList
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
            rowKey={record => record.id}
          />
        </div>
        {detailModalVisible?<Details
          {...detailsMethods}
          detailModalVisible={detailModalVisible}
          text={text}
           />:null}
        {upgradeListModalVisible?<UpgradeList
          {...upgradeListMethods}
          upgradeListModalVisible={upgradeListModalVisible}
          text={text}
          upGradeList={upGradeList}
        />:null}
      </Card>

    );
  }
}

//查看详情弹窗
class Details extends PureComponent {
  constructor(props) {
    super(props);
  }

  render() {
    const { detailModalVisible, handleDetailModalVisible,text} = this.props;
    return (
      <Modal
        destroyOnClose
        width={800}
        title="查看详情"
        visible={detailModalVisible}
        onCancel={() => handleDetailModalVisible(false)}
        footer={[
          <Button key="back" type="primary" onClick={() => handleDetailModalVisible()}>返回</Button>
        ]}
        className={styles.viewMore}
      >

        <Row>
          <Col md={12}>
          <FormItem {...formLayout} label="业务名称">
            {text.bmname}
          </FormItem>
        </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="版本号">
              {text.vmvernum}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="升级模式">
              {vmisforce[text.vmisforce]}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="升级包类型">
              {vmpackagetype[text.vmpackagetype]}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="升级包相对路径">
              {text.vmftppath}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="升级包大小">
              {text.vmpackagesize}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="升级包HASH值">
              {text.vmpackagehash}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="BC文件HASH值">
              {text.vmbchash}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="发布日期">
              {text.vmpublishdate}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="上传日期">
              {text.vmuploaddate}
            </FormItem>
          </Col>
          <Col md={24}>
            <FormItem labelCol={{span: 4}} wrapperCol={{span: 20}} label="发布说明">
              {text.vmpublishdesc}
            </FormItem>
          </Col>
      </Row>
      </Modal>
    );
  }
}

//升级记录
class UpgradeList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedRows: [],
    };
  }
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { text, getUpGrade } = this.props;
    // 分页请求
    getUpGrade(text,pagination.pageSize,pagination.current-1);
  };
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  render() {
    const {
      upgradeListModalVisible,
      handleUpgradeListModalVisible,
      upGradeList,
      text
    } = this.props;
    const {selectedRows} = this.state;
    const columns = [
      {
        title: '主机名称',
        dataIndex: 'hostName',
      },
      {
        title: '操作系统',
        dataIndex: 'operatingSystem',
      },
      {
        title: 'IP地址',
        dataIndex: 'ipAddr',
        width: '20%',
        render: (text) => (
          <div className={styles.colRemark} title={text}>
            {text}
          </div>
        )
      },
      {
        title: 'MAC地址',
        dataIndex: 'macAddr',
      },
      {
        title: '主机名称',
        dataIndex: 'hostName',
      },
      {
        title: '操作系统',
        dataIndex: 'operatingSystem',
      },
      {
        title: '内存大小',
        dataIndex: 'upgradeSize',
      },
      {
        title: '升级前版本',
        dataIndex: 'previousVersion',
      },
      {
        title: '升级结果',
        dataIndex: 'upgradeResult',
        render: (text) => (
        <span>
          {text==1?'成功':'失败'}
        </span>
        )
      },
      {
        title: '升级日期',
        dataIndex: 'upgradeDate',
        render: (text) => (
        <span>
          {moment(text).format('YYYY-MM-DD HH:mm:ss')}
        </span>
        )
      },
    ];
    return (
      <Modal
        destroyOnClose
        width={1000}
        title="查看升级记录"
        visible={upgradeListModalVisible}
        onCancel={() => handleUpgradeListModalVisible(false)}
        footer={[
          <Button key="back" type="primary" onClick={() => handleUpgradeListModalVisible()}>返回</Button>
        ]}
        className={styles.viewMore}
      >

        <Row>
          <Col md={12}>
            <FormItem {...formLayout} label="业务名称">
              {text.bmname}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="版本号">
              {text.vmvernum}
            </FormItem>
          </Col>
        </Row>
        <TableList
          selectedRows={selectedRows}
          data={upGradeList}
          columns={columns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
          hideRowSelection={true}
          rowKey={record => record.id}
          />
      </Modal>
    );
  }
}

export default versionMag;
